package olegroshka.src.com.bofa.olegroshka.analitics;

import java.math.BigDecimal;


public abstract class RangeRefundModelBase implements RefundModel {

	public BigDecimal calculate(BigDecimal salesAmount) {
		if (salesAmount == null) {
			new IllegalStateException("Sales amount can't be null.");
		}

		DiscountLevelDescriptor discountLevelInfo = 
				getDiscountLevelInfo(salesAmount);

		BigDecimal result = BigDecimal.ZERO;
		if (discountLevelInfo != null) {
			BigDecimal minValue = discountLevelInfo.getMin();
			DiscountLevelDescriptor discountLevel = discountLevelInfo;

			BigDecimal salesRemainder = salesAmount.add(minValue.negate());
			BigDecimal fixedDiscount = discountLevel.getCumulativeDiscountValue();

			result = fixedDiscount.add(salesRemainder.multiply(discountLevel.getRate()));
		}

		return result.setScale(2, BigDecimal.ROUND_HALF_DOWN);
	}

	protected abstract DiscountLevelDescriptor getDiscountLevelInfo(BigDecimal salesAmount);
}
